//引入express
const express = require('express')
//创建router
const router = express.Router()

//引入mysql
const mysql = require('mysql')
const { UCS2_ICELANDIC_CI } = require('mysql/lib/protocol/constants/charsets')
//引入数据库信息
const db = require('../db')
//引入sql文件，使用查询语句
const sql = require('../sql')

//创建连接
const connection = mysql.createConnection(db.mysql)
connection.connect()

//时间转化为字符串时间
function formatDateTime(date) {
    var y = date.getFullYear();  
        var m = date.getMonth() + 1;  
        m = m < 10 ? ('0' + m) : m;  
        var d = date.getDate();  
        d = d < 10 ? ('0' + d) : d;  
        var h = date.getHours();  
        h=h < 10 ? ('0' + h) : h;  
        var minute = date.getMinutes();  
        minute = minute < 10 ? ('0' + minute) : minute;  
        var second=date.getSeconds();  
        second=second < 10 ? ('0' + second) : second;  
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
}

//字符串时间转化为时间
function convertDateFromString(dateString) {
    if (dateString) { 
        var arr1 = dateString.split(" "); 
        var sdate = arr1[0].split('-'); 
        var hour =arr1[1].split(':')    
        var date = new Date(sdate[0], sdate[1]-1, sdate[2],hour[0],hour[1],hour[2]); 
        return date;
        } 
}

//查询所有订单
router.get('/selOrder',(req, res) => {
    connection.query(sql.order.selectOrder, (err, result) => {
        if (err) throw err;
        console.log(result)
        res.json(result)
    })  
})

//结算金额，生成订单
router.post('/insertOrder', async (req, res) => {
       
    req.body.products.map(item => {
        item.buyTime = formatDateTime(new Date())
        item.buyTime =convertDateFromString(item.buyTime)
        return item
        
    })
    const { phone,address,receiver} = req.body
    console.log(req.body)
    await req.body.products.forEach(item => {
        // console.log(item.name,'===',item)
        connection.query(sql.order.insertOrder, [parseInt(req.body.userId),item.teaId,item.buyTime,parseFloat(item.price)*item.number,item.number,0,0,address,phone,receiver], (err, result) => {
            if (err) throw err;
        })
    });
     
    /* req.body.products.forEach(item => {
        //给商家修改金额信息
        connection.query(sql.order.updateMoney, [parseFloat(item.price) * item.number, item.id], (err, result) => {
            if (err) throw err; 
        })
    }) */
    
    res.json({
        isInsert: true,
        msg:'订单添加成功'
    })
})

//查询用户订单
router.get('/selectUserOrder', (req, res) => {
    
    connection.query(sql.order.selectUserOrder,[req.query.userId], (err, result) => {
        if (err) throw err;
        result = result.reverse()
        // console.log(result)
         var index = 1
        result = result.map(item => {
            item.money = parseFloat(item.money).toFixed(2)+'元'
            item.index = index++
            item.buyTime = formatDateTime(item.buyTime)
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result) 
        res.json(result)
    })
})

//取消订单
router.post('/cancelOrder', (req, res) => {
    connection.query(sql.order.cancelOrder, [req.body.id], (err, result) => {
        if (err) throw err;
        // console.log(result)
        res.json({
            cancel:true
        })
    })
})

//退回金额
router.post('/refund', (req, res) => {
    let money = parseFloat(req.body.money).toFixed(2)
    connection.query(sql.order.refund, [money, req.body.userId], (err, result) => {
        if (err) throw err;
        console.log(result)
        res.json(result)
    })
})

//发货，修改订单状态
router.post('/modifyStatus', (req,res) => {
    connection.query(sql.order.modifyStatus, [req.body.id], (err, result) => {
        if (err) throw err;
        console.log(result)
        res.json({
            msg:'发货成功'
        })
    })
})

//发货修改库存获取茶叶的id
router.get('/getTeaId', (req, res) => {
    connection.query(sql.order.selTeaId, [req.query.id], (err, result) => {
        if (err) throw err
        res.json(result)
    })
})

//添加评论内容
router.post('/setEstimation', (req, res) => {
    let {estimation,id } = req.body
    connection.query(sql.order.setEstimation, [estimation, id], (err, result) => {
        if (err) throw err;
        res.json({
            msg:'评价成功！'
        }) 
    })
})

//获取评论内容
router.get('/getEstimation', (req, res) => {
    connection.query(sql.order.getEstimation, [req.query.id], (err, result) => {
        if (err) throw err
        res.json(result)
    })
})

//查询所有订单茶叶种类的数量
router.get('/selOrderTea', (req, res) => {
    connection.query(sql.order.selectOrder, async (err1, result1) => {
        // console.log("result2",result1)
        if (err1) throw err1
        let teaData = {
            black: 0,
            dark: 0,
            green: 0,
            yellow: 0,
            oolong: 0,
            white:0
        }
        await result1.forEach(item => {
            connection.query(sql.order.selectTeaNum, [item.teaId], (err2, result2) => {
                //  console.log("result2",result2)
                if (err2) throw err2
                if (result2[0].type === '白茶') {
                    teaData.white+= item.number
                } else if (result2[0].type === '乌龙茶') {
                    teaData.oolong +=item.number
                }else if (result2[0].type === '绿茶') {
                    teaData.green +=item.number
                }else if (result2[0].type === '黄茶') {
                    teaData.yellow +=item.number
                }else if (result2[0].type === '黑茶') {
                    teaData.dark +=item.number
                } else {
                    teaData.black +=item.number
                }
            })
        })
        setTimeout(() => {
            // console.log(teaData)
            res.json(teaData)
        },50)     
    })
})

//查询数据库的茶叶库存量
router.get('/selTeaStore', (req, res) => {
    connection.query(sql.order.selectTeaStore, [req.query.userId],(err, result) => {
        if (err) throw err;
        result = result.filter(item => {
            return item.store<50
        })
        res.json(result)
    })
})

//查询要添加到购物车中的茶叶库存量
router.get('/selOneTeaStore', (req, res) => {
    connection.query(sql.order.selectOneTeaStore, [req.query.teaId],(err, result) => {
        if (err) throw err;
        res.json(result)
    })
})


module.exports =router
